-- UITrainingHeroUpgrade
-- Create by zouyb
-- 训练室升阶界面

require "game/ui/form/training/UITrainingItemDesc"

-- UITrainingHeroUpgrade继承自Layer
UITrainingHeroUpgrade = class("UITrainingHeroUpgrade", function()
    return cc.Layer:create();
end);

function UITrainingHeroUpgrade.create(classId)
    return UITrainingHeroUpgrade.new(classId);
end

-- 内部函数声明
local resize;

-- 构造函数
function UITrainingHeroUpgrade:ctor(classId)
    -- 初始化
    self:setName("UITrainingHeroUpgrade");
    local node = cc.CSLoader:createNode("layout/training/TrainingHeroUpgrade.csb");
    self:addChild(node);
    self.node = node;
    self.classId = classId;

    -- self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘英雄星级
function UITrainingHeroUpgrade:redrawHeroStar(starNode, classId, starNum)
    local hero = PetM.getMyPet(classId);
    if not hero then
        return;
    end

    -- 获取英雄阶位
    local maxStarNum = PetM.getMaxUpgradeRank();
    if maxStarNum < 1 then
        maxStarNum = 1;
    end
    if maxStarNum < starNum then
        maxStarNum = starNum;
    end

    -- 生成星星层，直接挂到结点上
    local lightStarPath = "images/ui/symbol/star_little.png";
    local darkStarPath  = "images/ui/symbol/star_little2.png";

    -- 如果冈布奥已觉醒，使用橙色的星星
    if AwakeM.isCarved(classId) then
        lightStarPath = "images/ui/symbol/star_large3.png";
    end

    local layer = createStarLayerEx(starNum, maxStarNum, lightStarPath, darkStarPath, "center", -0.7);
    if not layer then
        return;
    end
    starNode:removeAllChildren();
    starNode:addChild(layer);
end

-- 重绘
function UITrainingHeroUpgrade:redraw()
    local node = self.node;
    local CT   = node:getChildByName("CT");
    local BT   = node:getChildByName("BT");

    -- 显示标题
    local titleLabel = findChildByName(node, "CT/title");
    titleLabel:setString(getLocStr("slime_upgrade"));
    TextStyleM.setTitleStyle(titleLabel);

    -- 显示描述
    local descLabel = findChildByName(CT, "desc");

    -- 获取升阶消耗时间
    local pet = PetM.getMyPet(self.classId);
    local costTime = FormulaM.invoke("CALC_PET_UPGRADE_COST_TIME", pet)

    local desc = "";
    local descFormat = "%s%s%s";
    if getLang() ~= "zh" and getLang() ~= "tw" then
        descFormat = "%s %s %s"
    end

    if costTime >= 3600 then
        local hours = costTime / 3600;
        desc = string.format(descFormat, getLocStr("slime_upgrade_time"), tostring(hours), getLocStr("hour"));
    elseif costTime >= 60 then
        local min = costTime / 60;
        desc = string.format(descFormat, getLocStr("slime_upgrade_time"), tostring(min), getLocStr("minute"));
    else
        local second = costTime;
        desc = string.format(descFormat, getLocStr("slime_upgrade_time"), tostring(second), getLocStr("second"));
    end
    descLabel:setString(desc);
    TextStyleM.setSubheadStyle(descLabel);

    local hero1 = findChildByName(node, "CT/hero1");
    local hero2 = findChildByName(node, "CT/hero2");

    local function initHero(node, rank, showWeapon)
        -- 设置为无法点击
        local bg = findChildByName(node, "bg");
        bg:setTouchEnabled(false);
        bg:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                -- 显示升阶详细信息
                local uiItemDesc = UITrainingItemDesc.create(self.classId, rank);
                UIMgr:getCurrentScene():addForm(uiItemDesc);
                AudioM.playFx("button_spell");
            end
        end);

        -- 显示头像
        local icon = findChildByName(node, "icon");
        local pet = PetM.getMyPet(self.classId);
        local fileName = pet:getIcon();
        local iconPath = getHeroIconPath(fileName);
        icon:loadTexture(iconPath);

        -- 出战中
        local activated = findChildByName(node, "activated");
        activated:setVisible(false);

        -- 星星
        local starNode = findChildByName(node, "star_node");
        self:redrawHeroStar(starNode, self.classId, rank);

        local weaponImg = findChildByName(node, "weapon");
        local medalImg = findChildByName(node, "medal");

        if showWeapon then
            weaponImg:setVisible(true);
            medalImg:setVisible(true);

            -- 武器
            local weaponClassId = EquipM.getHeroEquip(pet, EQUIP_TYPE_WEAPON, 1);
            if weaponClassId then
                local iconIndex = ItemM.query(weaponClassId, "icon");

                if haveItemSmallIcon(iconIndex) then
                    weaponImg:loadTexture(getItemSmallIconPath(iconIndex));
                    weaponImg:setScale(0.95);
                else
                    weaponImg:loadTexture(getItemIconPath(iconIndex));
                    weaponImg:setScale(0.4);
                end
            else
                weaponImg:setVisible(false);
            end

            -- 徽章
            local medalClassId = EquipM.getHeroEquip(pet, EQUIP_TYPE_MEDAL, 1);
            if medalClassId then
                local iconIndex = ItemM.query(medalClassId, "icon");
                if haveItemSmallIcon(iconIndex) then
                    medalImg:loadTexture(getItemSmallIconPath(iconIndex));
                    medalImg:setScale(0.95);
                else
                    medalImg:loadTexture(getItemIconPath(iconIndex));
                    medalImg:setScale(0.4);
                end
            else
                medalImg:setVisible(false);
            end
        else
           weaponImg:setVisible(false);
           medalImg:setVisible(false);
        end
    end

    initHero(hero1, pet:getRank(), true);
    initHero(hero2, pet:getRank() + 1);
end

-- 注册事件处理回调函数
function UITrainingHeroUpgrade:registerEventCallback()
    -- 注册获得焦点的回调
    EventMgr.register("UITrainingHeroUpgrade", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UITrainingHeroUpgrade" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UITrainingHeroUpgrade");

            -- 如果当前英雄还没开始升阶，则取消升阶
            if TrainingM.getState() == TrainingM.TRAINING_STATE_PREPARE then
                Operation.cmd_pet_cancel_training();
            end

            local uiTrainingMain = UIMgr.getCurrentScene():getFormByName("UITrainingMain");
            if uiTrainingMain then
                uiTrainingMain:setVisible(true);
            end
        elseif eventType == "enter" then
            local uiTrainingMain = UIMgr.getCurrentScene():getFormByName("UITrainingMain");
            if uiTrainingMain then
                uiTrainingMain:setVisible(false);
            end
        end
    end);
end

-- 注册点击事件
function UITrainingHeroUpgrade:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UITrainingHeroUpgrade");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确认按钮点击事件
    local btnOk = findChildByName(node, "CT/btn_ok");
    local function onOKClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then

            local ret = TrainingM.canUpgrade(self.classId);
            if ret ~= true then
                if ret == "hero_upgrade_hint" then
                    -- 训练室等级不足，提示玩家具体升级信息
                    local areaId = FormulaM.invoke("GET_TREE_BRANCH_DROP_MAP", ME.user, TrainingM.getLevel() + 1);
                    local mapName = DungeonAreaM.query(areaId, "name");
                    local msg = string.format(getLocStr(ret), PetM.query(self.classId, "name"), mapName);

                    showHint2(getLocStr("slime_note"), msg);
                    AudioM.playFx("button_spell");
                    return;
                end

                return alert(getLocStr(ret));
            end

            -- 向服务器发送开始升阶请求
            Operation.cmd_pet_start_training(self.classId);

            TrainingM.starUpgrade(self.classId);
            -- 选择宠物进行进阶事件
            EventMgr.fire(event.SELECT_PET_UPGRADE, {["class_id"] = self.classId, });

            if UIMgr.getCurrentScene():isOpen("UIHeroUpgradeRank") then
                UIMgr.getCurrentScene():removeFormByName("UIHeroUpgradeRank");
            end
            if UIMgr.getCurrentScene():isOpen("UIHeroMain") then
                UIMgr.getCurrentScene():removeFormByName("UIHeroMain");
            end

            UIMgr.getCurrentScene():removeFormByName("UITrainingHeroUpgrade");

            if UIMgr.getCurrentScene():isOpen("UITrainingMain") ~= true then
                local uiForm = UITrainingMain.create();
                UIMgr.getCurrentScene():addForm(uiForm);
            end

        end
    end

    btnOk:addTouchEventListener(onOKClick);
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(getLocStr("btn_text_ok"));
end

